package org.OpenGeoPortal.Download;

import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;

public class OgpConfigRetriever extends ConfigRetriever implements
		SearchConfigRetriever {
	public OgpConfigRetriever(String configFilePath){
		this.setConfigFilePath(configFilePath);
	}

	public String getSearchUrl() throws ParseException, IOException{
		this.readConfigFile();
		JSONObject jsonObject = (JSONObject) this.configContents.get("search");
		return (String) jsonObject.get("serviceAddress");
	}
	
	public String getSearchPort() throws ParseException, IOException{
		this.readConfigFile();
		JSONObject jsonObject = (JSONObject) this.configContents.get("search");
		Long searchPort = (Long) jsonObject.get("servicePort");
		return searchPort.toString();
	}
	
	public String getSearchType() throws ParseException, IOException{
		this.readConfigFile();
		JSONObject jsonObject = (JSONObject) this.configContents.get("search");
		return (String) jsonObject.get("serviceType");
	}
	
	public String getHome() throws ParseException, IOException{
		this.readConfigFile();
		return (String) this.configContents.get("homeInstitution");
	}
	
	public Boolean isOgp(){
		return true;
	}
	
	public String getArbitrary(String configKey) throws Exception {
		/*this only works for strings in the top level.  should eventually be more generic */
		this.readConfigFile();
		return (String) this.configContents.get(configKey);
	}

	@Override
	public String getWmsProxy(String institution, String accessLevel) throws ParseException, IOException {
		this.readConfigFile();
		JSONObject allInstitutionsObject = (JSONObject) this.configContents.get("institutions");
		JSONObject institutionObject = (JSONObject) allInstitutionsObject.get(institution);
		if (institutionObject.containsKey("proxy")){
			JSONObject proxyObject = (JSONObject) institutionObject.get("proxy");
			JSONArray accessArray = (JSONArray) proxyObject.get("accessLevel");
			if (accessArray.contains(accessLevel)||accessArray.contains(accessLevel.toLowerCase())){
				return (String) proxyObject.get("wms");
			} else {
				return null;
			}
		} else {
			return null;
		}
	}
}
